package com.wisdom.benefit.jufa.product;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wisdom.benefit.jufa.event.CallBackOtherInterface;
import com.wisdom.benefit.jufa.my.NewCollectionCodeActivity;
import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.utils.DataCleanManager;
import com.wisdom.benefit.jufa.utils.DialogUtil;
import com.wisdom.benefit.jufa.utils.ImageLoader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 收款户设置
 */
public class AccountSettingActivity extends BaseActivity implements CallBackOtherInterface {
    private RelativeLayout backRl, deleteRl;
    private ListView lv;
    private ArrayList<AccountSettingBean> datas;
    private AccountSettingAdapter accountSettingAdapter;
    private Dialog dialog;
    private View inflate;
    private TextView camera, isGetTv;
    private TextView pic;
    private ImageView dialogIv;
    private TextView cancel, toAli;
    private int isGet;
    private Long PassagewayId;
    private int PassagewayType;
    private RelativeLayout bgRl;
    private ImageView myIv;
    private Long userId;
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private ImageView iv;
    private Button btn;
    private static final String URL_FORMAT =
            "intent://platformapi/startapp?saId=10000007&" +
                    "clientVersion=3.7.0.0718&qrcode={urlCode}" +
                    "&_t=1472443966571#Intent;" + "scheme=alipayqr;package=com.eg.android.AlipayGphone;end";

    @Override
    protected int getLayout() {
        return R.layout.activity_account_setting;
    }

    @Override
    protected void initViews() {
        //列表
        lv = findViewById(R.id.account_setting_lv);
        //返回
        backRl = findViewById(R.id.account_setting_back);
        //是否是接单账户
        isGetTv = findViewById(R.id.account_setting_isGet);
        //删除
        deleteRl = findViewById(R.id.account_setting_delete);
        isGet = getIntent().getIntExtra("isGet", 3);
        PassagewayType = getIntent().getIntExtra("PassagewayType", 4);
        PassagewayId = getIntent().getLongExtra("PassagewayId", 1);
        userId = getIntent().getLongExtra("userId", 1);
        iv = findViewById(R.id.account_setting_iv);
        //新增收款码
        btn = findViewById(R.id.account_setting_btn);
        //图片背景
        bgRl = findViewById(R.id.account_setting_my_rl);
        //图片
        myIv = findViewById(R.id.account_setting_my_iv);
        setData();
        setClick();
    }

    private void setData() {
        if (PassagewayType == 1) {
            iv.setImageResource(R.mipmap.ali_icon);
        } else if (PassagewayType == 2) {
            iv.setImageResource(R.mipmap.wechat_icon);
        } else if (PassagewayType == 3) {
            iv.setImageResource(R.mipmap.transfer_accounts);
        } else if (PassagewayType == 4) {
            iv.setImageResource(R.mipmap.zhikouling);
        }
        if (isGet == 1) {
            isGetTv.setText("*此账户是本机接单账户");
            isGetTv.setTextColor(getResources().getColor(R.color.blue));
        } else {
            isGetTv.setText("*此账户不是本机接单账户");
            isGetTv.setTextColor(getResources().getColor(R.color.red_ff666b));
        }

    }

    /**
     * 监听事件
     */
    private void setClick() {
        bgRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bgRl.setVisibility(View.GONE);
            }
        });
        //返回
        backRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //删除
        deleteRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog();
            }
        });
        //新增收款码
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PassagewayType == 1 || PassagewayType == 2|| PassagewayType == 4) {
                    Intent intent = new Intent(AccountSettingActivity.this, NewCollectionCodeActivity.class);
                    intent.putExtra("PassagewayId", PassagewayId);
                    intent.putExtra("userId", userId);
                    intent.putExtra("PassagewayType", PassagewayType);
                    startActivity(intent);
                } else {
                    alipayTranAccSave(userId, PassagewayId);
                }

            }
        });
    }

    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    @Override
    public void callBackClick(int position) {
        if (datas.get(position).getReceivingAccount() == 0) {
            startDialog(datas.get(position).getUserIdCreate(), datas.get(position).getCodeId(), 1, datas.get(position).getBelongPassageway());

        } else {
            editPaymentCodeRecAcc(datas.get(position).getUserIdCreate(), datas.get(position).getCodeId(),
                    0, datas.get(position).getBelongPassageway());
        }

    }

    @Override
    public void callBackClickOther(int position) {
        paymentCodeDelete(datas.get(position).getUserIdCreate(), datas.get(position).getCodeId(), datas.get(position).getBelongPassageway());
    }

    @Override
    public void callIvBackClick(int position) {
        if (datas.get(position).getPassagewayId() == 3||datas.get(position).getPassagewayId() == 4) {
            newDialog(datas.get(position).getQrCode());
        } else {
            bgRl.setVisibility(View.VISIBLE);
            String base64 = datas.get(position).getQrCode();
            ImageLoader.loadImage(myIv, base64);
//            Bitmap decodedByte =  ZxingTool.createQRCodeBitmap(base64, 800, 800,"UTF-8","H", "1", Color.BLACK, Color.WHITE);
//            byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
//            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
//            myIv.setImageBitmap(decodedByte);
        }
    }

    public void show() {
        dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //填充对话框的布局
        inflate = LayoutInflater.from(getActivity()).inflate(R.layout.photo_other_dialog_item, null);
        //初始化控件
        camera = (TextView) inflate.findViewById(R.id.camera);
        pic = (TextView) inflate.findViewById(R.id.pic);
        cancel = (TextView) inflate.findViewById(R.id.cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCamera();
                dialog.dismiss();
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPhoto();
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    public void showPic(Bitmap bitmap) {
        dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //填充对话框的布局
        inflate = LayoutInflater.from(getActivity()).inflate(R.layout.photo_image_dialog_item, null);
        //初始化控件
//        camera = (TextView) inflate.findViewById(R.id.camera);
//        toAli = inflate.findViewById(R.id.to_ali);
        dialogIv = (ImageView) inflate.findViewById(R.id.photo_image_dialog_iv);
        dialogIv.setImageBitmap(bitmap);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    /**
     * 从系统相机选择图片来源
     */
    private void getCamera() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA_REQUEST);
    }

    /**
     * 从相册选择图片来源
     */
    private void getPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, PHOTO_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                switch (resultCode) {
                    case -1://-1表示拍照成功
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = (Bitmap) bundle.get("data");
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();

                        Matrix matrix = new Matrix();

                        matrix.setScale(0.5f, 0.5f);

                        Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),

                                bitmap.getHeight(), matrix, true);
                        Log.i("wechat", "压缩后图片的大小" + (bm.getByteCount() / 1024 / 1024)

                                + "M宽度为" + bm.getWidth() + "高度为" + bm.getHeight());

                        String a = bitmapToBase64(bm);
                        byte[] decodedString = Base64.decode(a, Base64.DEFAULT);
                        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        break;
                }
                break;

            case PHOTO_REQUEST://从相册取
                if (data != null) {
                    Uri uri = data.getData();
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                        String a = bitmapToBase64(bitmap);
                        byte[] decodedString = Base64.decode(a, Base64.DEFAULT);
                        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        showPic(decodedByte);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
                break;
        }
    }


    /*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private void dialog() {
        DialogUtil dialogUtil = new DialogUtil(AccountSettingActivity.this, AccountSettingActivity.this);
        dialogUtil.dialog("提示", "确定是否删除该通道？", "取消", "确定", "1");
        dialogUtil.setOnItemClickListener(new DialogUtil.OnItemClickListener() {
            @Override
            public void onItemCancelClick() {
                Log.d("onItemClick", "你点击了取消");
            }

            @Override
            public void onItemConfirmClick() {


            }

            @Override
            public void onItemValueConfirmClick(String a) {
                boolean b = DataCleanManager.clearAllCache(AccountSettingActivity.this);
                if (b == true) {
                    passagewayDelete(PassagewayId);
                }
            }
        });
    }

    /**
     * 使用账号时
     */
    private void startDialog(Long userIdCreate, Long codeId, int receivingAccount, Long belongPassageway) {
        DialogUtil dialogUtil = new DialogUtil(AccountSettingActivity.this, AccountSettingActivity.this);
        dialogUtil.dialog("提示", "确定使用此收款码？", "取消", "确定", "1");
        dialogUtil.setOnItemClickListener(new DialogUtil.OnItemClickListener() {
            @Override
            public void onItemCancelClick() {
                Log.d("onItemClick", "你点击了取消");
            }

            @Override
            public void onItemConfirmClick() {


            }

            @Override
            public void onItemValueConfirmClick(String a) {
                boolean b = DataCleanManager.clearAllCache(AccountSettingActivity.this);
                if (b == true) {
                    editPaymentCodeRecAcc(userIdCreate, codeId, receivingAccount, belongPassageway);
                }
            }
        });
    }

    /**
     * 删除通道
     */
    private void passagewayDelete(Long passagewayId) {
        addDisposable(RetrofitService.getNetService()
                .passagewayDelete((long) passagewayId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getCode() == 0) {
                        finish();
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("新增失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 收款码列表
     */
    private void userPassagewayCodeList(Long passagewayId, Long userId) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .userPassagewayCodeList(userId, (long) passagewayId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        datas = new ArrayList<>();
                        datas = response.getData();
                        //列表
                        accountSettingAdapter = new AccountSettingAdapter(datas, getActivity(), this);
                        lv.setAdapter(accountSettingAdapter);
                    } else {
                        datas = new ArrayList<>();
                        //列表
                        accountSettingAdapter = new AccountSettingAdapter(datas, getActivity(), this);
                        lv.setAdapter(accountSettingAdapter);
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 修改收款码状态
     */
    private void editPaymentCodeRecAcc(Long userIdCreate, Long codeId, int receivingAccount, Long belongPassageway) {
        addDisposable(RetrofitService.getNetService()
                .editPaymentCodeRecAcc(userIdCreate, codeId, receivingAccount, belongPassageway)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getCode() == 0) {
                        userPassagewayCodeList(PassagewayId, userId);
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("新增失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    /**
     * 删除收款码
     */
    private void paymentCodeDelete(Long userIdCreate, Long codeId, Long belongPassageway) {
        addDisposable(RetrofitService.getNetService()
                .paymentCodeDelete(userIdCreate, codeId, belongPassageway)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getCode() == 0) {
                        userPassagewayCodeList(PassagewayId, userId);
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("新增失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }


    /**
     * 支付宝转账新增
     */
    private void alipayTranAccSave(Long userIdCreate, Long belongPassageway) {
        addDisposable(RetrofitService.getNetService()
                .alipayTranAccSave(userIdCreate, belongPassageway)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getCode() == 0) {
                        String jumpUrl = response.getData().getJumpUrl();
                        if (isAliPayInstalled(this) == true) {
                            startAlipay(AccountSettingActivity.this, jumpUrl);
                        } else {

                            Toast.makeText(this, "当前手机尚未安装支付宝", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("新增失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    public boolean startAlipay(Activity activity, String urlCode) {
        return startIntentUrl(activity, URL_FORMAT.replace("{urlCode}", urlCode));
    }

    public boolean startIntentUrl(Activity activity, String intentUrl) {
        try {
            Intent intent = Intent.parseUri(intentUrl, Intent.URI_INTENT_SCHEME);
            activity.startActivity(intent);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 检测是否安装支付宝
     *
     * @param context
     * @return
     */
    public static boolean isAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }


    @Override
    protected void onResume() {
        super.onResume();
        userPassagewayCodeList(PassagewayId, userId);
    }

    private void newDialog(String msg) {
        DialogUtil dialogUtil = new DialogUtil(AccountSettingActivity.this, AccountSettingActivity.this);
        dialogUtil.newdialog(msg, "确定", "1");
        dialogUtil.setOnItemClickListener(new DialogUtil.OnItemClickListener() {

            @Override
            public void onItemCancelClick() {

            }

            @Override
            public void onItemConfirmClick() {
                boolean a = DataCleanManager.clearAllCache(AccountSettingActivity.this);
                if (a == true) {

                }
            }

            @Override
            public void onItemValueConfirmClick(String a) {

            }
        });
    }
}
